﻿using PHMEE.DTOS.FleetMonitor;
using PHMEE.DTOS.StatusMonitor;
using PHMEE.IServices.FleetMonitor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PHMEE.Services.FleetMonitor
{
    public class FleetVesselMonitorAppService : PHMEEAppService, IFleetVesselMonitorAppService
    {
        private readonly IFleetRepository fleetRepository;
        private readonly IVesselRepository vesselRepository;

        public FleetVesselMonitorAppService(IFleetRepository fleetRepository, IVesselRepository vesselRepository)
        {
            this.fleetRepository = fleetRepository;
            this.vesselRepository = vesselRepository;
        }

        /// <summary>
        /// 获取船队船舶列表
        /// </summary>
        /// <param name="fleetId"></param>
        /// <returns></returns>
        public async Task<List<FleetVesselModel>> GetFleetVesselParams(Guid? fleetId)
        {
            List<FleetVesselModel> list = new List<FleetVesselModel>();

            var query = await fleetRepository.PhmeeGetQuery();

            query = query.WhereIf(fleetId != null, item => item.Id == fleetId);

            var fleets = await AsyncExecuter.ToListAsync(query);

            var fleetIds = fleets.Select(item => item.Id).ToList();

            var queryVessel = await vesselRepository.PhmeeGetQuery();

            queryVessel = queryVessel.Where(item => fleetIds.Contains(item.FleetId)).OrderByDescending(item => item.CreationTime);

            var vesselsAll = await AsyncExecuter.ToListAsync(queryVessel);

            foreach (var fleet in fleets)
            {
                var vessels = vesselsAll.Where(item => item.FleetId == fleet.Id).ToList();

                var model = new FleetVesselModel();

                model.FleetId = fleet.Id;

                model.FleetName = fleet.Name;

                foreach (var vessel in vessels)
                {
                    var modelVessel = new VesselMainModel();

                    modelVessel.VesselId = vessel.Id;

                    modelVessel.VesselName = vessel.DisplayName;

                    modelVessel.IMO = vessel.IMO;

                    modelVessel.CallSign = vessel.CallSign;

                    modelVessel.Type = vessel.Type;

                    modelVessel.TypeString = vessel.Type.ToString();

                    modelVessel.DeadWeightTon = vessel.DeadWeightTon;

                    modelVessel.NetTon = vessel.NetTon;

                    modelVessel.GrossTon = vessel.GrossTon;

                    modelVessel.FlagState = vessel.FlagState;

                    modelVessel.ClassificationSociety = vessel.ClassificationSociety;

                    model.Vessels.Add(modelVessel);

                }

                list.Add(model);

            }

            return list;

        }
    }
}
